<template>
    <el-row>
        <el-col :span="24">
            <div class="header_inner">
                <div class="log">
                    <img src="../../assets/img/logo.png" />
                </div>
                <div class="login_register" v-if="user.isLogin">
                    <div class="head_portrait">
                        <span @click="goMeSapce(userInfo)" v-if="$route.name == 'index'">我的空间</span>
                        <a v-else @click="goHome"><i class="iconfont icon-home"></i>首页</a>
                        <el-dropdown>
                            <span class="el-dropdown-link">
                                <el-avatar style="margin: 0 5px 0 10px" :size="60" @error="errorHandler"
                                    :src="userInfo.photo | pictureUrl">
                                    <img :src="sex=='1'?headPortrait:headPortraitFemale" />
                                </el-avatar>
                            </span>
                            <el-dropdown-menu slot="dropdown" placement="bottom">
                                <!-- <el-dropdown-item @click.native="goMessage(user.userId)">消息</el-dropdown-item> -->
                                <el-dropdown-item @click.native="goMeSapce(userInfo)" v-if="($route.name !== 'index' && (otherUserInfo.userid && userInfo.id !== otherUserInfo.userid))
                                || (studentToSpace && $route.name !== 'index')">我的空间</el-dropdown-item>
                                <el-dropdown-item @click.native="goPersonal(user.userId)">个人中心</el-dropdown-item>
                                <el-dropdown-item @click.native="logOut(user)">退出登录</el-dropdown-item>
                            </el-dropdown-menu>
                            
                        </el-dropdown>
                        <span>{{ userInfo.name || user.userName }}</span>
                        <div class="messge">
                        <el-badge :is-dot="stringToBoolean(messageDot) || isdos" class="item" @click.native="goMessage(user.userId)" v-if="$route.name != 'message'">消息</el-badge>
                        <el-button type="text" class="item" @click.native="messageBack()" v-else>返回</el-button>
                    </div>
                    <!-- <div class="setup">
                        <el-dropdown trigger="click">
                            <span class="el-dropdown-link">
                                设置
                            </span>
                            <el-dropdown-menu slot="dropdown">
                                <el-dropdown-item>主页装扮</el-dropdown-item>
                                <el-dropdown-item @click.native="goPersonal()">个人中心</el-dropdown-item>
                                <el-dropdown-item>退出登录</el-dropdown-item>
                            </el-dropdown-menu>
                        </el-dropdown>
                    </div> -->
                    <div class="setup1">
                        <span class="el-dropdown-link">
                            <el-popover
                                placement="top"
                                width="160"
                                v-model="visible">
                                <p>确定退出管理界面吗？</p>
                                <div style="text-align: right; margin: 0">
                                    <el-button size="mini" type="text" @click="visible = false">取消</el-button>
                                    <el-button type="primary" size="mini" @click="schoolManagement(false)">退出</el-button>
                                </div>
                                <el-button type="text" slot="reference" v-if="isShowManagement" @click="manageShow">退出管理</el-button>
                            </el-popover>
                            <label  class="item" @click="schoolManagement(true)" v-if="manageV && !isShowManagement && isManager">管理中心</label>
                        </span>
                    </div>
                    </div>
                </div>
                <div class="login_register" v-else>
                    <el-row v-if="!user.isLogin">
                        <el-button type="primary" size="mini" plain @click="goHome" v-if="$route.name !== 'index'">返回首页</el-button>
                        <el-button type="primary" size="mini" plain @click="$router.push({ path: '/login' })" v-else>空间登录
                        </el-button>
                    </el-row>
                </div>
            </div>
        </el-col>
    </el-row>
</template>

<script>
    import {
        getCookie
    } from "../../utils/auth";
    import {
        websocketcUrl
    } from '@/utils/common'
    import {
        mapState
    } from "vuex";
    export default {
        computed: {
            ...mapState({
                isShowManagement: state => state.commonModule.isShowManagement,
                isManager: state => state.commonModule.isManager,
                studentToSpace: state => state.commonModule.studentToSpace,
                messageDot: state => state.commonModule.messageDot,
                user: state => state.userModule.user,
                userInfo: state => state.userModule.userInfo,
                otherUserInfo: state => state.userModule.otherUserInfo,
            })
        },
        created() {
            // this.$store.dispatch("userModule/findByUserIdInfo")
            // console.log(JSON.parse(getCookie('userInfo')),getCookie('casSessionId'))
            if(JSON.parse(getCookie('userInfo')) == null && this.$route.path.split('/')[1] != 'login'){
                // console.log(this.$route.query.type)
                if(this.$route.query.type == 'renrentong'){
                    this.$store.dispatch("userModule/findByUserIdInfo")
                }
            }
            if(this.user.userId){
                this.getIsDots(this.user.userId)
                // this.initWebSocket()
            }
        },
        destroyed() {
            this.websocketclose()
        },
        mounted() {
            // this.getIsDots(this.userInfo.id)
            if(this.$route.path.split('/')[1] == 'school' || this.$route.path.split('/')[1] == 'class' || this.$route.path.split('/')[1] == 'research'){
                this.manageV = true
            }else{
                this.manageV = false
            }
            if (this.$route.name === "login") {
                this.user.isLogin = false;
            }
        },
        data() {
            return {
                isdos: false,
                manageV: false,
                visible:false,
                headPortrait: require("@a/img/男.png"),
                headPortraitFemale: require("@a/img/女.png")
            };
        },
        watch: {
        　　user: {
        　　　　handler(newValue, oldValue) {
                    if(newValue.userId){
                        this.getIsDots(newValue.userId)
                    }
                   this.websocketclose()
                //    this.initWebSocket()
                },
        　　　　deep: true
        　　}
        },
        methods: {
            stringToBoolean(params){
                if(params =='true'){
                    return true
                }else{
                    return false
                }
            },
            // 获取全局提醒消息红点
            getIsDots(params) {
                this.$store.dispatch('messageModule/getMsgList', {
                    userid: params,
                }).then(res => {
                    if (res.data.code === 200) {
                        if(res.data.result.unreadNum >0){
                            this.isdos = true
                            this.$store.commit('commonModule/INIT_MESSAGEDOT',true)
                        }else{
                            this.isdos = false
                            this.$store.commit('commonModule/INIT_MESSAGEDOT',false)
                        }
                    }
                })
            },
            // 消息返回时验证消息是否已经读完
            messageBack(){
                this.$router.go(-1);
                this.getIsDots(this.user.userId)
            },
            manageShow(){
                this.visible = true
            },
            schoolManagement(params){
                this.$store.commit('commonModule/INIT_ISSHOWMANAGEMENT',params);
                this.visible =false
            },
            initWebSocket: function () {
                // WebSocket与普通的请求所用协议有所不同，ws等同于http，wss等同于https
                var webSocketUrl = 'ws://'+websocketcUrl+'websocket/common' + this.user.userId
                this.websock = new WebSocket(webSocketUrl);
                this.websock.onopen = this.websocketonopen;
                this.websock.onerror = this.websocketonerror;
                this.websock.onmessage = this.websocketonmessage;
                this.websock.onclose = this.websocketclose;
            },
            websocketonopen: function () {
                // console.log("common连接成功");
            },
            websocketonerror: function (e) {
                // console.log("common连接发生错误");
            },
            websocketonmessage: function (e) {
                // console.log(e.data)
                if(e.data =='common'){
                    this.$store.commit('commonModule/INIT_MESSAGEDOT',true)
                    this.getIsDots(this.user.userId)
                }
            },
            websocketclose: function (e) {
                // console.log("common关闭连接");
            },
            //退出登录
            logOut() {
                this.$store.commit("userModule/LOGOUT_CLEAR_USER");
                // 打包环境--服务器
                // window.open('','_self')
                // window.close()
                // 开发环境
                // // setTimeout(function (){
                // //     console.log("退出登录")
                    this.$router.replace('/')
                    this.$router.go(0);
                // // }, 1000);
            },
            errorHandler() {
                return true;
            },
            // 消息
            goMessage(userId) {
                this.$router.push({
                    path: "/message",
                    query: userId
                });
            },
            // 个人中心
            goPersonal(userId) {
                this.$store.commit('commonModule/INIT_STUDENTTOSPACE',false);
                let type = this.type;
                this.$router.push({
                    path: "/personal/",
                    query: userId
                });
            },
            // 个人空间
            goMeSapce(user) {
                this.$store.commit('commonModule/INIT_STUDENTTOSPACE',false);
                 // 8教师，6学生，9家长，9527学校，1000班级，100011教研
                switch (user.role_id || user.roleid) {
                    case 6:
                    case 8:
                    case 9:
                        this.$store.commit('userModule/INIT_OTHERUSERINFO_DATA', user)
                        this.$router.push({
                            path: "/students",
                            query: user.id
                        });
                        break
                    case 7:
                        this.$store.commit('commonModule/INIT_ISMANAGER',true);
                        this.$store.commit('userModule/INIT_OTHERUSERINFO_DATA', user)
                        this.$router.push({
                            path: "/school/schoolHomePage",
                            query: {
                                others: user
                            }
                        });
                        break
                    case 1000:
                        this.$store.commit('commonModule/INIT_ISMANAGER',true);
                        this.$store.commit('userModule/INIT_OTHERUSERINFO_DATA', user)
                        this.$router.push({
                            path: "/class/classHomePage",
                            query: {
                                others: user
                            }
                        });
                        break
                    case 100011:
                        this.$store.commit('commonModule/INIT_ISMANAGER',true);
                        this.$store.commit('userModule/INIT_OTHERUSERINFO_DATA', user)
                        this.$router.push({
                            path: "/research/researchOther/researchOtherHome",
                            query: {
                                others: user
                            }
                        });
                        break
                    default:
                        this.$message.warning('请登录后重试')
                        break;
                }
            },
            // 回系统首页
            goHome() {
                this.$store.commit('commonModule/INIT_STUDENTTOSPACE',false);
                this.manageV =false
                this.$store.commit('commonModule/INIT_ISSHOWMANAGEMENT',false);
                this.$router.push({
                    path: "/index"
                });
            }
        }
    };
</script>

<style lang="scss" scoped>
    .header_inner {
        width: 82%;
        box-sizing: border-box;
        padding: 10px 0;
        margin: 0 auto;
        display: flex;
        align-items: center;
        justify-content: space-between;

        &>.log {
            height: 100%;

            &>img {
                height: 40px;
            }
        }
    }

    .head_portrait {
        display: flex;
        align-items: center;
        cursor: pointer;
    }

    .el-dropdown-link {
        cursor: pointer;
        color: #409eff;
    }

    .el-icon-arrow-down {
        font-size: 12px;
    }
    .messge {
        cursor: pointer;
        margin: 0px 30px 0 50px;
    }

    .setup {
        margin-top: 0px;
        cursor: pointer;
    }
    .setup1 {
        margin-left: 20px;
        cursor: pointer;
    }
</style>